package com.xiaoyu.code;

import org.apache.ibatis.type.JdbcType;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * ${DESCRIPTION}
 *
 * @author muxiaoyu
 * @create 2017-03-03 9:57
 **/
public class CommonJdbcExector {
    public Object selectOne(AdminDataSource dataSource, String sql) throws Exception {
        Connection connection = getConnection(dataSource);
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        ResultSetMetaData metaData = resultSet.getMetaData();
        Class<?> clazz = Class.forName("com.xiaoyu.entity.User");
        Object object = clazz.newInstance();

        while (resultSet.next()) {
            for (Field field : clazz.getDeclaredFields()) {
                for (int i = 1; i < metaData.getColumnCount(); i++) {
                    if (field.getName().equals(metaData.getColumnName(i))) {
                        field.setAccessible(true);
                        field.set(object, resultSet.getObject(i));
                    }
                }
            }
        }
        closeResource(resultSet, statement, null, connection);
        return object;
    }

    /**
     * 关闭资源
     *
     * @param resultSet
     * @param statement
     * @param preparedStatement
     * @param connection
     * @throws SQLException
     */
    private void closeResource(ResultSet resultSet, Statement statement, PreparedStatement preparedStatement, Connection connection) throws SQLException {
        if (resultSet != null) {
            resultSet.close();
        }
        if (statement != null) {
            statement.close();
        }
        if (preparedStatement != null) {
            preparedStatement.close();
        }
        if (connection != null) {
            connection.close();
        }

    }


    Connection getConnection(AdminDataSource dataSource) throws Exception {
        Class.forName(dataSource.getDriverClass());
        return DriverManager.getConnection(dataSource.getUrl(), dataSource.getUser(), dataSource.getPassword());
    }
}
